#include "PreCompile.hpp"
#include "SimpleTasks.hpp"
#include "Project.hpp"

namespace BuildNG
{
  //////////
  // CopyTask
  void CopyTask::init()
  {
    Glib::RefPtr<TaskTypeInfo> type_info(new TaskTypeInfo);
    type_info->set_xml_tag_name("copy");
    type_info->set_create_func_from_ctor<CopyTask>();
    task_types_registry.register_type(type_info);
  } 

  void CopyTask::shutdown()
  {
    // nothing
  }

  void CopyTask::load_from_xml(const Xml::Element &xml)
  {
    src = xml.get_attribute_value("src");
    dest = xml.get_attribute_value("dest");
  }

  void CopyTask::run(BuildContext &context) const
  {
    std::vector<Glib::ustring> files_to_copy = super_glob(src,context.get_cur_dir(),SuperGlobFlag_AbsolutePath);
    if(files_to_copy.size() == 0)
      throw Exception("File to copy not found.");

    if(Glib::file_test(dest,Glib::FILE_TEST_IS_DIR))
    { 
      for(int i = 0;i < (int)files_to_copy.size();i++)
      {
        Glib::ustring cur_dest = Glib::build_filename(Glib::build_filename(
          context.get_cur_dir(),
          dest),
          Glib::path_get_basename(files_to_copy[i]));

        copy_file(files_to_copy[i],cur_dest);
      }
    }
    else
    {
      if(files_to_copy.size() != 1)
      {
        throw Exception("If the destination path is a file "
          "(and not a directory), the source path can only be a single file.");
      }

      Glib::ustring abs_dest;
      if(Glib::path_is_absolute(dest))
        abs_dest = dest;
      else
        abs_dest = Glib::build_filename(context.get_cur_dir(),dest);

      copy_file(files_to_copy[0].c_str(),abs_dest.c_str());
    }
  }
}

